package com.gzz.orchid.common.webmvc.securityjwt;

import com.alibaba.fastjson2.JSON;
import com.gzz.orchid.common.webmvc.support.HttpResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录失败处理器
 *
 * @author higmd
 */
public class DelegateLoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {
        //        Result result = Result.errorCustom(ResponseStatusEnum.PAYMENT_USER_INFO_ERROR);
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        String restult = null;
        int code = 500;
        if (exception instanceof AccountExpiredException) {
            restult = "账号已过期";
        } else if (exception instanceof BadCredentialsException) {
            restult = "用户密码错误";
        } else if (exception instanceof CredentialsExpiredException) {
            restult = "密码过期";
        } else if (exception instanceof DisabledException) {
            restult = "用户被禁用";
        } else if (exception instanceof LockedException) {
            restult = "用户被锁";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            restult = "用户不存在";
        }
        //        response.getWriter()
        //                .println(JSON.toJSONString(HttpResult.failure().message(restult)));
        String msg = JSON.toJSONString(HttpResult.failure().message(restult));
        out.write(msg.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
